//
//  Home_VC.m
//  KaChing_App
//
//  Created by Jordan Robert Yust on 3/21/09.
//  Copyright 2009 __MyCompanyName__. All rights reserved.
//

#import "Home_VC.h"
#import "Constants.h"

@implementation Home_VC

@synthesize dateFormatter;
@synthesize numberFormatter;
@synthesize userName;
@synthesize oneDay_Perf_AsString;
@synthesize oneWeek_Perf_AsString;
@synthesize imagePlaceHolder;
@synthesize standingsTableView;
@synthesize wallTableView;
@synthesize availableCashLabel;
@synthesize shortCollateralLabel;
@synthesize totalValueLabel;
@synthesize wall;
@synthesize dataManager;
@synthesize timeStampInputFormatter;
@synthesize timeStampOutputFormatter;

/*
// Override initWithNibName:bundle: to load the view using a nib file then perform additional customization that is not appropriate for viewDidLoad.
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) {
        // Custom initialization
    }
    return self;
}
*/

/*
// Implement loadView to create a view hierarchy programmatically.
- (void)loadView {
}
*/


// Implement viewDidLoad to do additional setup after loading the view.
- (void)viewDidLoad
{
	// Debugging
	NSLog(@"\n\nInside Home_VC!!\nRemotekey: %@\nUserID: %d", [dataManager remoteKey], [dataManager userID]);
	
	
	[self createFormatters];	// Create/allocate the formatters
	[self refreshData];			// Retrieve data from kaChing
	
	self.title = userName;	// Updates the title with the user's name
	
	[super viewDidLoad];
}

/*
 ------------------------------------------------------------------------
 UITableView Protocol methods
 ------------------------------------------------------------------------
 */

#pragma mark -
#pragma mark UITableView Protocol methods

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
	if (tableView == standingsTableView)
		return 1;
	else if(tableView == wallTableView)
		return 1;
	else 
		return 1;
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
	if (tableView == standingsTableView)
		return 3;
	else if(tableView == wallTableView)
	{
		//get the number of wall posts
		return [[wall objectForKey:@"posts"] count];
	}
	else 
		return 1;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
	
	static NSString *CellIdentifier = @"Cell";
	
	UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
	
	/* If the tableview is the standings table */
	if (tableView == standingsTableView)
	{
		if (cell == nil)
		{
			cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier] autorelease];
	
			cell.selectionStyle = UITableViewCellSelectionStyleNone;	// Mark cell as unable to be selected
		}
		
		/* Create the top row */
		if (indexPath.row == 0)				
		{
			[self configure_FirstRow_Standings:cell];
		}
		/* Create the 'today' row */
		else if (indexPath.row == 1)
		{
			[self configure_SecondRow_Standings:cell];
		}
		/* Create the 'week' row */
		else if (indexPath.row == 2)
		{
			[self configure_ThirdRow_Standings:cell];
		}
	}
	/* If the tableview is the wall table */
	else if(tableView == wallTableView)
	{
		//get the htmlContent
		NSString *htmlContent = [[[wall objectForKey:@"posts"] objectAtIndex:indexPath.row] objectForKey:@"htmlContent"];
		//get the user that posted
		NSString *user = [[[[wall objectForKey:@"posts"] objectAtIndex:indexPath.row] objectForKey:@"author"] objectForKey:@"fullName"];
		//get the timeStamp
		NSString *timeStamp = [[[wall objectForKey:@"posts"] objectAtIndex:indexPath.row] objectForKey:@"timestamp"];
		//Run the timeStamp through the timeStampDateformatter
		NSDate *timeStampDate = [timeStampInputFormatter dateFromString:timeStamp];
		CGRect postViewFrame = CGRectZero;
		CGRect picFrame = CGRectZero;
		CGRect timeFrame = CGRectZero;
		if (cell == nil)
		{
			cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier] autorelease];
			cell.selectionStyle = UITableViewCellSelectionStyleNone;	// Mark cell as unable to be selected

			//create the label for posts without hyperlinks in them
			UILabel *postView = [[UILabel alloc] initWithFrame:postViewFrame];
			[postView setFont:[UIFont fontWithName:@"Arial" size:14]];
			
			[cell.contentView addSubview:postView];
			
			//memory management
			[postView release];
			
			timeFrame.size.width = cell.contentView.frame.size.width - 30;  timeFrame.size.height = cell.contentView.frame.size.height - 30;
			
			//specify location of frame within cell
			timeFrame.origin.x=30; timeFrame.origin.y=0;
			
			//create the label for posts without hyperlinks in them
			UILabel *timeSenderLabel = [[UILabel alloc] initWithFrame:timeFrame];
			//set label attributes
			timeSenderLabel.textColor = [UIColor grayColor];
			timeSenderLabel.font = [UIFont fontWithName:@"Helvetica Neue" size:12];
			
			//[timeSenderLabel 
			[cell.contentView addSubview:timeSenderLabel];
			
			//memory management
			[timeSenderLabel release];
		}
		
		//get the number of lines for the post
		
		//get the length of the content
		NSInteger numLines = ([htmlContent length] / 43) - (([htmlContent length] % 43) / 43) + 2;

		//debug
		NSLog(htmlContent);
		//debug
		NSLog(@"Row: %d Author: %@ \n\tNumber of Characters: %d \n \tNumber of Lines: %d", indexPath.row, user, [htmlContent length], numLines);
		
		//create a frame with the proper number of lines
		//postViewFrame.size.width = cell.contentView.frame.size.width-15;  postViewFrame.size.height = 43*numLines-25;
		
		//specify location of frame within cell
		//postViewFrame.origin.x=0; postViewFrame.origin.y=25;
		//[(UILabel *)[cell.contentView.subviews objectAtIndex:0] setFrame:postViewFrame];
		
		//set timeStamp equal to the newly formatted date
		timeStamp = [timeStampOutputFormatter stringFromDate:timeStampDate];
		
		
		//debug
		
		//[htmlContent sizeWithFont:[UIFont fontWithName:@"Arial" size:14]  constrainedToSize:maxSize lineBreakMode:UILineBreakModeWordWrap]
		
		//set the size of the HTML content label
		CGSize maxSize = CGSizeMake(300, 10000);
		CGRect tempFrame;
		tempFrame.size = [htmlContent sizeWithFont:[UIFont fontWithName:@"Arial" size:14] constrainedToSize:maxSize lineBreakMode:UILineBreakModeWordWrap];
		tempFrame.origin.x = 0; tempFrame.origin.y = 25;
		[[cell.contentView.subviews objectAtIndex:0] setFrame:tempFrame];
		
		//put the HTML content in the label
		[[cell.contentView.subviews objectAtIndex:0] setText:htmlContent];
		[(UILabel *)[cell.contentView.subviews objectAtIndex:0] setNumberOfLines:0];
		
		//add the sender and the time that it was sent to the timeSenderLabel
		[[cell.contentView.subviews objectAtIndex:1] setText:[NSString stringWithFormat:@"%@ wrote on %@", user, timeStamp]];
		
		/*Code to add in the new image to the cell*/
		//specify frame size
		picFrame.size.width=25; picFrame.size.height=25;
		
		//specify location of frame within cell
		picFrame.origin.x=0; picFrame.origin.y=0;
		
		//create a new asynchronous image object 
		AsyncImageView* asyncImage = [[[AsyncImageView alloc]
									   initWithFrame:picFrame] autorelease];
		
		//set the tag so that we know the image has been added
		asyncImage.tag = 999;
		
		//get the stock image url
		if([[[[wall objectForKey:@"posts"] objectAtIndex:indexPath.row] objectForKey:@"author"] objectForKey:@"picture"]!= NULL)
		{
			NSURL* url = [NSURL URLWithString:(NSString *) [[[[wall objectForKey:@"posts"] objectAtIndex:indexPath.row] objectForKey:@"author"] objectForKey:@"picture"]];
			
			[asyncImage loadImageFromURL:url];
			
			[cell.contentView addSubview:asyncImage];
		}
	}

	//Debug
	//NSLog(@"height: %d width: %d", [cell.contentView.subviews objectAtIndex:0].frame.size.width, [cell.contentView.subviews objectAtIndex:0].frame.size.height);
	return cell;
}

/*
 This method allows me to create a custom height for each tableViewCell, based on the content
 of each cell. So, I search through the htmlContent of the posts to determine if they are longer
 than the max number of characters on a line, and if they are I add the appropriate space to the
 tableViewRow
*/
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
	if(tableView == wallTableView)
	{

		//get the html string corresponding to this row
		NSString *htmlContent = [[[wall objectForKey:@"posts"] objectAtIndex:indexPath.row] objectForKey:@"htmlContent"];
		
		CGSize maxSize = CGSizeMake(300, 10000);
		return [htmlContent sizeWithFont:[UIFont fontWithName:@"Arial" size:14] constrainedToSize:maxSize lineBreakMode:UILineBreakModeWordWrap].height + 27;

	}
	else{
		if(indexPath.row == 0)
			return 50;
		else
			return 30;
	}
	
}

/*
This method specifies the Header of the current section in the tableView.
NOTE: This method is part of the UITableViewDataSource Protocol.
*/
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
	if(tableView == wallTableView)
	{
		return @"Wall";
	}
	else if(tableView == standingsTableView)
		return @"";
	else
		return @"Error";
}

/*
 This method specifies the Header of the current section in the tableView.
 NOTE: This method is part of the UITableViewDataSource Protocol.
 */
//- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
//{
//	return @"Standings";
//}

/*
 - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
 }
 */

/*
 - (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
 
 if (editingStyle == UITableViewCellEditingStyleDelete) {
 }
 if (editingStyle == UITableViewCellEditingStyleInsert) {
 }
 }
 */

/*
 - (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
 return YES;
 }
 */

/*
 - (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
 }
 */

/*
 - (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
 return YES;
 }
 */

/*
 ------------------------------------------------------------------------
 Standings TableViewCell Configuration methods
 ------------------------------------------------------------------------
 */

#pragma mark -
#pragma mark Standings TableViewCell Configuration methods

-(void) configure_FirstRow_Standings:(UITableViewCell *) cell
{
	// NOTE: Iphone screen width: 320 pixels
	// NOTE: Each UITableViewCell is 320 X 45
	// NOTE: CGRectMake(x_pos, y_pos, width, height);
	UIColor *firstRowColor = [UIColor customSeaFoamGreen];

	UILabel *tempLabel = [[UILabel alloc] initWithFrame:returnLabelDimensions];
	tempLabel.backgroundColor = firstRowColor;
	tempLabel.textAlignment = UITextAlignmentCenter;
	tempLabel.font = [UIFont boldSystemFontOfSize:16.0];
	tempLabel.textColor = [UIColor whiteColor];
	tempLabel.text = @"Return";
	[cell.contentView addSubview:tempLabel];
	[tempLabel release];
}


-(void) configure_SecondRow_Standings:(UITableViewCell *) cell
{
	// NOTE: Iphone screen width: 320 pixels
	// NOTE: Each UITableViewCell is 320 X 45
	// NOTE: CGRectMake(x_pos, y_pos, width, height);
	
	UIColor *secondRowColor = [UIColor whiteColor];
	
	UILabel *tempLabel = [[UILabel alloc] initWithFrame:firstLabel_Dimensions];
	tempLabel.backgroundColor = secondRowColor;
	tempLabel.textAlignment = UITextAlignmentRight;
	tempLabel.font = [UIFont systemFontOfSize:16.0];
	tempLabel.text = @"Today:";
	[cell.contentView addSubview:tempLabel];
	[tempLabel release];
	
	tempLabel = [[UILabel alloc] initWithFrame:secondLabel_Dimensions];
	tempLabel.backgroundColor = secondRowColor;
	tempLabel.textAlignment = UITextAlignmentCenter;
	tempLabel.font = [UIFont systemFontOfSize:16.0];
	
	if ([oneDay_Perf_AsString floatValue] < 0)
	{
		
		tempLabel.text = [oneDay_Perf_AsString substringFromIndex:2];
		tempLabel.textColor = [UIColor redColor];
	}
	else if ([oneDay_Perf_AsString floatValue] > 0)
	{
		tempLabel.text = oneDay_Perf_AsString;
		tempLabel.textColor = [UIColor customGreen];
	}
	else
	{
		/* If it is up type "-0.0", remove the '-' */
		if ([oneDay_Perf_AsString characterAtIndex:1] == '-')
			tempLabel.text = [oneDay_Perf_AsString substringFromIndex:2];
		else
			tempLabel.text = oneDay_Perf_AsString;
		
		tempLabel.textColor = [UIColor blackColor];
	}
	
	[cell.contentView addSubview:tempLabel];
	[tempLabel release];
}

-(void) configure_ThirdRow_Standings:(UITableViewCell *) cell
{
	// NOTE: Iphone screen width: 320 pixels
	// NOTE: Each UITableViewCell is 320 X 45
	// NOTE: CGRectMake(x_pos, y_pos, width, height);
	
	UIColor *thirdRowColor = [UIColor whiteColor];
	
	UILabel *tempLabel = [[UILabel alloc] initWithFrame:firstLabel_Dimensions];
	tempLabel.backgroundColor = thirdRowColor;
	tempLabel.textAlignment = UITextAlignmentRight;
	tempLabel.font = [UIFont systemFontOfSize:16.0];
	tempLabel.text = @"Week:";
	[cell.contentView addSubview:tempLabel];
	[tempLabel release];
	
	
	tempLabel = [[UILabel alloc] initWithFrame:secondLabel_Dimensions];
	tempLabel.backgroundColor = thirdRowColor;
	tempLabel.textAlignment = UITextAlignmentCenter;
	tempLabel.font = [UIFont systemFontOfSize:16.0];
	
	
	if ([oneWeek_Perf_AsString floatValue] < 0)
	{
		tempLabel.text = [oneWeek_Perf_AsString substringFromIndex:1];
		tempLabel.textColor = [UIColor redColor];
	}
	else if ([oneWeek_Perf_AsString floatValue] > 0)
	{
		tempLabel.text = oneWeek_Perf_AsString;
		tempLabel.textColor = [UIColor customGreen];
	}
	else
	{
		/* If it is up type "-0.0", remove the '-' */
		if ([oneWeek_Perf_AsString characterAtIndex:1] == '-')
			tempLabel.text = [oneWeek_Perf_AsString substringFromIndex:1];
		else
			tempLabel.text = oneWeek_Perf_AsString;
		
		tempLabel.textColor = [UIColor blackColor];
	}
	
	[cell.contentView addSubview:tempLabel];
	[tempLabel release];
}


/*
 ------------------------------------------------------------------------
 Private methods
 ------------------------------------------------------------------------
 */

#pragma mark -
#pragma mark Private methods

- (void) createFormatters
{
	/* DATE FORMATTER CREATION */
	dateFormatter = [[NSDateFormatter alloc] init];
	[dateFormatter setDateFormat:@"yyyy-MM-dd"];
	
	//format the timeStamp
	timeStampInputFormatter = [[NSDateFormatter alloc] init];
	timeStampOutputFormatter = [[NSDateFormatter alloc] init];
	[timeStampInputFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm"];
	[timeStampOutputFormatter setDateFormat:@"MM/dd/yyyy 'at' HH:mm"];
	
	/* NUMBER FORMATTER CREATION */
	numberFormatter = [[NSNumberFormatter alloc] init];
	[numberFormatter setFormatterBehavior:NSNumberFormatterBehavior10_4];
	[numberFormatter setPositiveFormat:@"###0.0%"];
	[numberFormatter setNegativeFormat:@"###0.0%"];
	NSLocale *usLocale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US"];
	[numberFormatter setLocale:usLocale];
	[usLocale release];
}

- (IBAction) refreshData
{
	/* Obtain the date one week ago today (the format needed for kaChing is YYYY-MM-DD) */
	NSDate *oneWeekDate = [NSDate dateWithTimeIntervalSinceNow:-(7 * secondsPerDay)];
	NSString *formattedDate = [dateFormatter stringFromDate:oneWeekDate];
	
	/* KaChing API calls */
	NSDictionary *performanceDictionary_OneMonth = [[[dataManager getPerformance:formattedDate] retain] objectForKey:@"performance"];	// Get one week's worth of performance data
	NSDictionary *userProfile = [[dataManager getUser] retain];			// Get the user's profile from kaChing
	NSDictionary *portfolio = [[dataManager getPortfolio] retain];
	
	[self setUserName:[userProfile objectForKey:@"fullName"]];  // Set the name of the profile. NOTE: 'userName' is an instance variable
	
	//add the available cash to the availableCash label
	NSNumberFormatter *currencyFormatter = [[NSNumberFormatter alloc] init];
	[currencyFormatter setPositiveFormat:@"#,##0.00"];
	[currencyFormatter setNegativeFormat:@"#,##0.00"];
	availableCashLabel.text = [NSString stringWithFormat:@"$%@",
							   [currencyFormatter stringFromNumber:
								[NSNumber numberWithFloat:
								 [[portfolio objectForKey:@"availableCash"] 
								  floatValue]]]];
	shortCollateralLabel.text = [NSString stringWithFormat:@"$%@",
							   [currencyFormatter stringFromNumber:
								[NSNumber numberWithFloat:
								 [[portfolio objectForKey:@"shortCollateral"] 
								  floatValue]]]];
	totalValueLabel.text = [NSString stringWithFormat:@"$%@",
								 [currencyFormatter stringFromNumber:
								  [NSNumber numberWithFloat:
								   [[portfolio objectForKey:@"totalValue"] 
									floatValue]]]];
	
	[currencyFormatter release];
	
	/****  Retrieve display pic here ****/
	
	//create a frame for the AsyncImageView 
	CGRect frame;
	frame.size.width = imagePlaceHolder.frame.size.width;  frame.size.height = imagePlaceHolder.frame.size.height;
	//specify location of frame within cell
	frame.origin.x=0; frame.origin.y=0;
	
	//Get the url 
	NSURL* url;
	if ([userProfile objectForKey:@"picture"] == nil){
		NSLog(@"nil url!!!");
	url = [NSURL URLWithString:@"http://www.bestweekever.tv/bwe/images/2008/05/OMFG%20MONKEY%20NIPS2.JPG"];}
	else
		url = [NSURL URLWithString:[userProfile objectForKey:@"picture"]];
	
	//create a new Asynchronous image which has methods to retrieve an image from a url Asynchronously
	AsyncImageView* asyncImage = [[[AsyncImageView alloc] 
								   initWithFrame:frame] autorelease];
	
	[asyncImage loadImageFromURL:url];
	
	[imagePlaceHolder addSubview:asyncImage];
	
	//Get the user's wall
	self.wall = [dataManager getWall];
	

/*** NOTE: At this point, retrieving the user profile is finished (above).  Now, retrieve the performance data (below) ***/
	
	NSArray *performanceArray_Unsorted = [performanceDictionary_OneMonth allKeys];	// Get all dates for the past week (unsorted)
	
	/* Sort the dates and store them in another array.  NOTE: The array is in reverse sorted order.  (I.e., the
	 farthest date back is at index 0 and yesterday's date is stored at the last index of the array). */
	NSArray *performanceArray_Sorted = [performanceArray_Unsorted sortedArrayUsingSelector:@selector(caseInsensitiveCompare:)];

	/***** At this point, the array contains all dates in reverse sorted order. *****/
	
	float currentPerformance = 1.0;
	
	/* Start from most recent date and loop to farthest date */
	for (int i = [performanceArray_Sorted count] - 1; i >= 0; i--)
	{
		NSString *curKey = [performanceArray_Sorted objectAtIndex:i];
		currentPerformance *= [[performanceDictionary_OneMonth valueForKey:curKey] floatValue];
		
		NSLog(@"%d. Key: %@     Value: %f", i, curKey, [[performanceDictionary_OneMonth valueForKey:curKey] floatValue]);
		
		/* If the date corresponds to yesterday.. */
		if (i == [performanceArray_Sorted count] - 1)
		{
			NSNumber *oneDay_Perf_AsNum = [NSNumber numberWithFloat:(currentPerformance - 1)];
			oneDay_Perf_AsString = [[numberFormatter stringFromNumber:oneDay_Perf_AsNum] retain];
			
			NSLog(@"**** Calculate today's performance:%f, %@", [oneDay_Perf_AsNum floatValue], [numberFormatter stringFromNumber:oneDay_Perf_AsNum]);
		}
		/* If the date corresponds to one week ago */
		else if (i == 0)
		{
			NSNumber *oneWeek_Perf_AsNum = [NSNumber numberWithFloat:(currentPerformance - 1)];
			oneWeek_Perf_AsString = [[numberFormatter stringFromNumber:oneWeek_Perf_AsNum] retain];
			
			NSLog(@"**** Calculate week's performance:%f, %@", [oneWeek_Perf_AsNum floatValue], [numberFormatter stringFromNumber:oneWeek_Perf_AsNum]);
		}
	}

	[self.standingsTableView reloadData];
	[self.wallTableView reloadData];
	
	[userProfile release];	// Memory Management: No longer need the userProfile Dictionary. Therefore release it.
	[performanceDictionary_OneMonth release];
}


#pragma mark -

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning]; // Releases the view if it doesn't have a superview
    // Release anything that's not essential, such as cached data
}


- (void)dealloc
{
	[dateFormatter release];
	[numberFormatter release];
	[userName release];
	[oneDay_Perf_AsString release];
	[oneWeek_Perf_AsString release];
	[imagePlaceHolder release];
	[standingsTableView release];
	[wallTableView release];
	[availableCashLabel release];
	[shortCollateralLabel release];
	[totalValueLabel release];
	[wall release];
	[dataManager release];
	[timeStampInputFormatter release];
	[timeStampOutputFormatter release];
    [super dealloc];
}


@end
